package zzu.xjc.http;

import zzu.xjc.http.util.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Author Xiejc
 * @Date 2021/8/6 10:00
 * @Description
 * @Since version-1.0
 */
public class Acceptor {
    Workers workers;
    private Selector selector;
    private ServerSocketChannel serverChannel;
    private int port;

    Acceptor(){

    }
    void inject(Workers workers){
        this.workers = workers;
    }
    void init(int port) throws IOException {
        this.port = port;
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.bind(new InetSocketAddress(port));
        selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    }
    void start(){
        new Thread(this::accept,"Acceptor").start();
    }
    private void accept(){
        Logger.info("Acceptor Start, Port : " + port);
        try {
            while (true){
                selector.select();
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()){
                    SelectionKey key = iter.next();
                    if (key.isAcceptable()){
                        SocketChannel clientChannel = serverChannel.accept();
                        clientChannel.configureBlocking(false);
                        workers.register(clientChannel);
                    }
                    iter.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
